package com.cloudkinto.controller.orderinput;


import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.service.headercontainer.vo.HeaderContainerValueAndRateReq;
import com.cloudkinto.service.headercontainer.vo.HeaderFeeSetRequest;
import com.cloudkinto.service.orderinput.OrderInputService;
import com.cloudkinto.service.orderinput.vo.*;
import com.cloudkinto.service.product.ProductInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张永远
 * @since 2020-06-08
 */
@RestController
@Api(tags = "订单入库模块")
@RequestMapping("/api/admin/orderInput")
public class OrderInputController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderInputController.class);

    @Autowired
    private OrderInputService service;
    @Autowired
    private ProductInfoService productInfoService;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        return service.addInit(getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @GetMapping("/addInitByStorageId/{id}")
    @ApiOperation(value = "获取库位初始化", notes = "获取库位初始化")
    public SingleResult addInitByStorageId(@PathVariable("id") Long id) {
        return service.addInitByStorageId(id);
    }

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated OrderInputAddReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId, companyId));
    }

    @UserSessionRequired
    @PutMapping("markIn")
    @ApiOperation(value = "商品整箱录入", notes = "商品录入")
    public SingleResult markIn(@RequestBody @Validated InputOrderMarkSingleReq req) {
        Long userId = getCurrentUserId();
        return service.markIn(req, userId);
    }

    @UserSessionRequired
    @PostMapping("allocationStorage")
    @ApiOperation(value = "操作、分配仓库", notes = "分配仓库")
    public SingleResult allocationStorage(@RequestBody @Validated OperateReq req) {
        service.allocationStorage(req, getCurrentUserId());
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("markInInit")
    @ApiOperation(value = "商品整箱录入初始化", notes = "商品整箱录入初始化")
    public SingleResult markInInit(@RequestParam Long id) {
        return service.markInInit(id);
    }

    @UserSessionRequired
    @PutMapping("markInSingle")
    @ApiOperation(value = "商品分箱子录入", notes = "商品录入")
    public SingleResult markIn(@RequestBody @Validated InputOrderMarkReq req) {
        Long userId = getCurrentUserId();
        return service.markInSingle(req, userId);
    }

    @UserSessionRequired
    @GetMapping("markInSingleInit")
    @ApiOperation(value = "商品分箱录入初始化", notes = "商品整箱录入初始化")
    public SingleResult markInSingleInit(@RequestParam String packageId) {
        return service.markInSingleInit(packageId);
    }

    @UserSessionRequired
    @GetMapping("storageList")
    @ApiOperation(value = "获取仓库列表", notes = "获取仓库列表")
    public SingleResult storageList() {
        return service.storageList();
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    public SingleResult updateInit(@PathVariable("id") Long id) {
        return service.updateInit(id, getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated OrderInputUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("auditInit")
    @ApiOperation(value = "审核初始化", notes = "审核初始化")
    public SingleResult auditInit() {
        return SingleResult.success(service.auditInit());
    }

    @UserSessionRequired
    @GetMapping("auditStatusInit")
    @ApiOperation(value = "修改订单状态初始化", notes = "修改订单状态初始化")
    public SingleResult auditStatusInit() {
        return SingleResult.success(service.auditStatusInit());
    }

    @UserSessionRequired
    @PostMapping("audit")
    @ApiOperation(value = "审核|修改状态", notes = "审核")
    public SingleResult audit(@RequestBody AuditReq req) {
        return service.audit(req, getCurrentUserId());
    }

    @UserSessionRequired
    @PostMapping("setUpCost")
    @ApiOperation(value = "设置费用", notes = "设置费用")
    public SingleResult setUpCost(@RequestBody SetUpCostReq req) {
        return service.setUpCost(req, getCurrentUserId());
    }

    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getCurrentUserId(), getCompanyId());
    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "companyId", value = "公司id"),
            @ApiImplicitParam(name = "shopId", value = "店铺id"),
            @ApiImplicitParam(name = "storageId", value = "仓库id"),
            @ApiImplicitParam(name = "transportType", value = "转运类型"),
            @ApiImplicitParam(name = "sendOutType", value = "运输类型"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult listPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String status = request.getParameter("status");
        String company = request.getParameter("companyId");
        String shopId = request.getParameter("shopId");
        String storageId = request.getParameter("storageId");
        String keyword = request.getParameter("keyword");
        String current = request.getParameter("current");
        String transportType = request.getParameter("transportType");
        String sendOutType = request.getParameter("sendOutType");
        String size = request.getParameter("pageSize");
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        map.put("status", status);
        if (companyId != null) {
            map.put("companyId", companyId + "");
        }
        if (StringUtils.isNotBlank(company)) {
            map.put("companyId", company);
        }

        map.put("transportType", transportType);
        map.put("sendOutType", sendOutType);
        map.put("shopId", shopId);
        map.put("storageId", storageId);
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        return service.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/productListPage")
    @ApiOperation(value = "商品（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "productType", value = "产品类型"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult productListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String companyIdc = request.getParameter("companyId");
        String productType = request.getParameter("productType");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        if (companyId != null) {
            map.put("companyId", String.valueOf(companyId));
        } else {
            map.put("companyId", companyIdc);
        }

        map.put("productType", productType);
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        return productInfoService.getListPage(map);
    }

    @UserSessionRequired
    @PostMapping("/importExcel")
    @ApiOperation(value = "导入入库单信息", notes = "导入入库单信息")
    public SingleResult uploadExcel(MultipartFile file) throws IOException {
        Long userId = getCurrentUserId();
        return SingleResult.success(service.importExcel(file, getCompanyId()));
    }

    @UserSessionRequired
    @GetMapping("/exportPackagePdf")
    @ApiOperation(value = "导出箱标文件", notes = "导出箱标文件")
    public void exportPackagePdf(Long id, HttpServletResponse response) throws IOException {
        Long userId = getCurrentUserId();
        service.exportPackagePdf(id, response);
    }

    @UserSessionRequired
    @GetMapping("/exportProductPdf")
    @ApiOperation(value = "导出產品标文件", notes = "导出產品标文件")
    public SingleResult exportProductPdf(Long id, HttpServletResponse response) throws IOException {
        Long userId = getCurrentUserId();
        return service.exportProductCodePdf(id, response);
    }

    @UserSessionRequired
    @GetMapping("fbaReturnInit")
    @ApiOperation(value = "fba转运初始化", notes = "fba转运")
    public SingleResult fbaReturnInit(@RequestParam(value = "id") Long id) {
        Long userId = getCurrentUserId();
        return service.fbaReturnInit(id, userId);
    }



    @UserSessionRequired
    @GetMapping("/setPriceInit")
    @ApiOperation(value = "设置费用初始化", notes = "查询初始化")
    public SingleResult setPriceInit(int type,long id) {
        return service.setPriceInit(type,id);
    }

    @UserSessionRequired
    @PostMapping("/setPrice")
    @ApiOperation(value = "设置费用", notes = "查询初始化")
    public SingleResult setPrice(@RequestBody HeaderFeeSetRequest request) {
        return service.setPriceItem(request);
    }

//    @UserSessionRequired
//    @PostMapping("/setValueAndRate")
//    @ApiOperation(value = "设置货值和关税比", notes = "查询初始化")
//    public SingleResult setValueAndRate(@RequestBody HeaderContainerValueAndRateReq req) {
//        return service.setValueAndRate(req.getOrderId(), req.getValue(), req.getRate());
//    }
//
//    @UserSessionRequired
//    @GetMapping("/setValueAndRateInit")
//    @ApiOperation(value = "设置货值和关税比初始化", notes = "查询初始化")
//    public SingleResult setValueAndRateInit(Long orderId) {
//        return service.setValueAndRateInit(orderId);
//    }


    @UserSessionRequired
    @GetMapping("/exportHeaderFeePage")
    @ApiOperation(value = "导出头程账单明细", notes = "查询初始化")
    public void exportHeaderFeePage(Long orderId, HttpServletResponse response) {
        service.exportHeaderFeePage(orderId, response);
    }

    @UserSessionRequired
    @GetMapping("/exportPackageInvoice")
    @ApiOperation(value = "导出入库清单", notes = "导出入库清单")
    public void exportPackageInvoice(Long id, HttpServletResponse responseBody) {
        service.exportPackageInvoice(id, responseBody);
    }


    @UserSessionRequired
    @GetMapping("/printBarCodePdf")
    @ApiOperation(value = "下载产品标", notes = "下载产品标")
    @ApiImplicitParams({@ApiImplicitParam(name = "length", value = "长",required = true),
            @ApiImplicitParam(name = "width", value = "宽", required = true),
            @ApiImplicitParam(name = "id", value = "入库单id", required = true)})
    public void printBarCodePdf(HttpServletRequest request, HttpServletResponse response)  {
        String length = request.getParameter("length");
        String width = request.getParameter("width");
        String id = request.getParameter("id");

        Map<String, String> map = new HashMap<>();

        String commoditySku = request.getParameter("commoditySku");
        String storageSku = request.getParameter("storageSku");
        String fnSku = request.getParameter("fnSku");
        String madeInChina = request.getParameter("madeInChina");
        String printDate = request.getParameter("printDate");
        String productName = request.getParameter("productName");
        String productSpec = request.getParameter("productSpec");

        if (StringUtils.isNotBlank(commoditySku)) {
            map.put("commoditySku", commoditySku);
        }
        if (StringUtils.isNotBlank(storageSku)) {
            map.put("storageSku", storageSku);
        }
        if (StringUtils.isNotBlank(fnSku)) {
            map.put("fnSku", fnSku);
        }
        if (StringUtils.isNotBlank(madeInChina)) {
            map.put("madeInChina", madeInChina);
        }
        if (StringUtils.isNotBlank(printDate)) {
            map.put("printDate", printDate);
        }
        if (StringUtils.isNotBlank(productName)) {
            map.put("productName", productName);
        }
        if (StringUtils.isNotBlank(productSpec)) {
            map.put("productSpec", productSpec);
        }


        service.printBarCodePdf(map, Long.parseLong(id),Integer.parseInt(length), Integer.parseInt(width),response);
    }

}

